/**
 * Append an image result into the result list
 * @param {Object} image Object containing {url, width, height}
 */
function appendImageResult(image, provider) {
	var style = " style='";
	if(parseInt(image.width) < 200) {
		style += "width:" + image.width + "px";
	}
	style += "'";
	$("ul").append("<li class='" + provider + "'><a href='" + image.url + "' target='_blank'><img src='" + image.url + "' " + style + "/></a><span class='watermark'></span></li>");
}

/**
 * Show the search as having started
 * @param {String} queryString The query string as typed by the user
 */
function showSearchStarted(queryString) {
	$("p").show();
}

/**
 * Show the search as having ended
 * @param {String} queryString The query string as typed by the user
 */
function showSearchEnded(queryString) {
	$("p").hide();
	$("input").focus();
	document.location.hash = encodeURIComponent(queryString);
}

function searchBing(q) {
	showSearchStarted(q);

	var qe = "animated gif " + q;
	var url = "http://api.search.live.net/json.aspx?Appid=3ADDCCC3955413788D24BBDEDDD6498F40C3C9D5&query=" + qe + "&sources=image&JsonType=callback&JsonCallback=?";
	$.getJSON(url, function(data) {
		var images = data.SearchResponse.Image.Results;
		if (!images) {
			return;
		}
		for(var i = 0; i < images.length; i++) {
			if(images[i].ContentType != "image/gif") {
				continue;
			}
			appendImageResult({url: images[i].MediaUrl, width: images[i].Width, height: images[i].Height}, "bing");
		}

		showSearchEnded(q);
	});
}

function searchGoogle(q) {
	showSearchStarted(q);

	var qe = "animated gif " + q;
	var url = "https://ajax.googleapis.com/ajax/services/search/images?v=1.0&rsz=8&q=" + qe + "&callback=?";
	$.getJSON(url, function(data) {
		var images = data.responseData.results;
		for(var i = 0; i < images.length; i++) {
			appendImageResult({url: images[i].unescapedUrl, width: images[i].width, height: images[i].height}, "google");
		}

		showSearchEnded(q);
	});
}
